package thread;

import java.util.concurrent.locks.LockSupport;

public class 交替打印 {
    public static void foobar(int n) throws InterruptedException {
        FooBar fooBar = new FooBar(n);

        Thread tf = new Thread(fooBar::foo);
        Thread tb = new Thread(fooBar::bar);
        fooBar.setTb(tb);
        fooBar.setTf(tf);

        tf.start();
        tb.start();

        tf.join();
        tb.join();
    }
    public static void main(String[] args) throws InterruptedException {
        交替打印.foobar(5);
    }
}
class FooBar {
    private int n;
    private Thread tf;
    private Thread tb;
    public FooBar(int n) {
        this.n = n;
    }
    public void setTf(Thread tf) {
        this.tf = tf;
    }
    public void setTb(Thread tb) {
        this.tb = tb;
    }
    public void foo () {
        for (int i = 0; i < n; i++) {
            System.out.print("foo");
            LockSupport.unpark(tb);
            LockSupport.park();
        }
    }
    public void bar () {
        for (int i = 0; i < n; i++) {
            LockSupport.park();
            System.out.print("bar");
            LockSupport.unpark(tf);
        }
    }
}